﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;

namespace SocketClient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int port = 2000;
                string host = "127.0.0.1";

                IPAddress ip = IPAddress.Parse(host);

                IPEndPoint ipe = new IPEndPoint(ip, port);

                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                Console.WriteLine("Conneting...");

                s.Connect(ipe);//连接服务器

                string sendStr = "hello!This is a socket test";

                byte[] bs = Encoding.ASCII.GetBytes(sendStr);//把字节串编码为字接数组

                Console.WriteLine("Send Message");

                s.Send(bs, bs.Length, 0);//发送信息


                /*接收服务器返回的信息*/

                string recvStr = string.Empty;

                byte[] recvBytes = new byte[1024];

                int bytes = s.Receive(recvBytes, recvBytes.Length, 0);

                recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);

                Console.WriteLine("client get message:{0}", recvStr);//显示服务器返回信息

                s.Close();
            }
            catch (SocketException ex)
            {
                Console.WriteLine("SocketException:{0}", ex);
            }
            Console.WriteLine("Press Enter to Exit");


        }
    }
}
